//
//  DataManager.swift
//  downloadImage
//
//  Created by Galaxy on 2022/6/21.
//  xpath 获取数据

import UIKit
import Ji

class DataManager: NSObject {
    
    enum XPathError: Error {
        case getContentFail
    }
    
    /// 获取列表数据
    /// - Parameters:
    ///   - website: 数据
    ///   - page: 页码
    func getListData(website:WebsiteModel,page:Int,success:@escaping (_ listArr:[ArticleModel])->(),failure:@escaping (_ error:Error)->()){
        var urlStr = ""
        if website.type == 1 {
//        https://lensdump.com/a/Rvwfb/?page=2&seek=2022-10-22+17:09:24.1yBpvQ
            if page == 1 {
                urlStr = website.detailUrl
            }else{
                if let nextUrl = UserDefaults.standard.object(forKey: "lensdump") {
                    urlStr = website.detailUrl+"&page=\(page)&\(nextUrl)"
                }
            }
        }
        DispatchQueue.global().async {
            let jiDoc = Ji.init(htmlURL: URL.init(string: urlStr)!)
            if jiDoc == nil {
                failure(XPathError.getContentFail)
            }else{
                DispatchQueue.main.async {
                    var articleArr:[ArticleModel] = []
                    var detailXpath = ""
                    if website.type == 1 {
                        detailXpath = "//div[contains(@class,'list-item')]/@data-url-short"
                        // 下一页地址
                        let nextXpath = "//a[@data-pagination='next']/@href"
                        let nextNodeArr = jiDoc?.xPath(nextXpath)
                        if nextNodeArr!.count > 0 {
                            // 存在下一页
                            let nextUrl = nextNodeArr![0].content
                            let nextUrlArr = nextUrl?.components(separatedBy: "&")
                            UserDefaults.standard.setValue(nextUrlArr?.last, forKey: "lensdump")
                        }else{
                            if page > 1 {
                                success(articleArr)
                                return;
                            }
                        }
                    }
                    let detailNodeArr = jiDoc?.xPath(detailXpath)
                    if detailNodeArr!.count > 0 {
                        for item in detailNodeArr! {
                            let article = ArticleModel.init()
                            if website.type == 1 {
                                article.detailUrl = item.content!
                                if !article.detailUrl!.starts(with: "http") {
                                    article.detailUrl = "https://lensdump.com" + article.detailUrl!
                                }
                            }
                            article.fatherId = website.identifier
                            article.type = website.type
                            articleArr.append(article)
                        }
                    }
                    success(articleArr)
                }
            }
        }
    }
    // 获取详情数据
    func getDetailData(article:ArticleModel,success:@escaping (_ listArr:[ImageModel])->(),failure:@escaping (_ error:Error)->()){
        let urlStr = article.detailUrl
        DispatchQueue.global().async {
            let jiDoc = Ji.init(htmlURL: URL.init(string: urlStr!)!)
            if jiDoc == nil {
                DispatchQueue.main.async {
                    failure(XPathError.getContentFail)
                }
            }else{
                DispatchQueue.main.async {
                    var imageArr:[ImageModel] = []
                    var imageNodeArr:[JiNode]?
                    if article.type == 1 {
                        let imageXpath = "//div[@id='image-viewer-container']/img/@src"
                        imageNodeArr = jiDoc?.xPath(imageXpath)
                        if imageNodeArr!.isEmpty {
                            let imageXpath = "//meta[@property='og:image']/@content"
                            imageNodeArr = jiDoc?.xPath(imageXpath)
                            
                        }
                    }
                    if imageNodeArr!.count > 0 {
                        for item in imageNodeArr! {
                            let image = ImageModel.init()
                            image.articleId = article.identifier
                            if article.type == 1 {
                                image.imgUrl = item.content!.replacingOccurrences(of: ".md", with: "")
                            }
                            imageArr.append(image)
                        }
                    }
                    success(imageArr)
                }
            }
        }
    }
}
